package com.sptus.web.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sptus.common.constant.CommonConstant;
import com.sptus.common.core.controller.BaseController;
import com.sptus.common.core.domain.AjaxResult;
import com.sptus.common.core.domain.entity.SysRole;
import com.sptus.common.core.domain.entity.SysUser;
import com.sptus.common.core.redis.RedisCache;
import com.sptus.system.utils.GmailSendVerificationCode;
import com.sptus.common.utils.SecurityUtils;
import com.sptus.common.utils.StringUtils;
import com.sptus.framework.service.BaseCommonService;
import com.sptus.system.domain.SptInstallerRegistry;
import com.sptus.system.service.ISysRoleService;
import com.sptus.system.service.ISysUserService;
import com.sptus.system.service.SptInstallerRegistryService;
import com.sptus.web.config.DataLoaderConfig;
import com.sptus.web.entity.SptUserRole;
import com.sptus.web.service.ISptUserRoleService;
import com.sptus.web.service.impl.SptUserServiceImpl;
import com.sptus.web.vo.SignUpVO;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@RestController
@Api(tags = "cloud安装")
@RequestMapping("/sys/cloud/Installation")
public class InstallationController extends BaseController {

    @Autowired
    SptUserServiceImpl sptUserService;
    @Autowired
    ISptUserRoleService userRoleService;

    @Autowired
    ISysRoleService  sysRoleService;

    @Autowired
    SptInstallerRegistryService  sptInstallerRegistryService;
    public  static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    @Autowired
    private BaseCommonService baseCommonService;
    @Autowired
    RedisCache redisUtil;

    @Autowired
    private ISysUserService userService;

    //获得app注册列表
    @GetMapping("signInstallation")
    public AjaxResult  signInstallation(String search , @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                        @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
        Page<SptInstallerRegistry> page = new Page<>(pageNo, pageSize);
        QueryWrapper<SptInstallerRegistry> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(search),"user_name",search);
        Page<SptInstallerRegistry> sptInstallerRegistryPage = sptInstallerRegistryService.getBaseMapper().selectPage(page, queryWrapper);
        return AjaxResult.success(sptInstallerRegistryPage);
    };

    //同意申请安装人员
    @PostMapping("saveInstallation")
    public AjaxResult  SaveInstallation(@RequestBody SignUpVO signUpVO){

        SptInstallerRegistry byId = sptInstallerRegistryService.getById(signUpVO.getUserId());
        QueryWrapper<SptInstallerRegistry> wrapper=new QueryWrapper<>();
        byId.setAuditorName(getUsername());
        byId.setAuditorId(getUserId()+"");
        byId.setConsumerType("2");
        if(byId!=null){
            if (signUpVO.getIsApprove()){
                SptUserRole sptUserRole = new SptUserRole();
                sptUserRole.setRoleId("XZ");
                sptUserRole.setUserId(byId.getUserId());
                userRoleService.save(sptUserRole);
                wrapper.eq("user_id",byId.getUserId());
                byId.setStatus("1");
                sptInstallerRegistryService.update(byId,wrapper);
            }else {
                byId.setStatus("2");
                sptInstallerRegistryService.update(byId,wrapper);
            }
        }
        return AjaxResult.success();
    };

    @PostMapping("deleteInstallation")
    public AjaxResult  deleteInstallation(@RequestBody SignUpVO signUpVO){
        boolean b = sptInstallerRegistryService.removeById(signUpVO.getUserId());
        return toAjax(b);
    };
    @GetMapping("getRole")
    public AjaxResult  getRole(){
        List<SysRole> sysRoles = sysRoleService.getRoleList();
        return AjaxResult.success(sysRoles);
    };





    //获得cloud用户注册列表
    @GetMapping("platformConsumerList")
    public  AjaxResult appConsumerList(  String search , @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                        @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
        List<Object>  listKey= redisUtil.getListKey("signUpUserToken:");
        ArrayList<SysUser> sysUsers = new ArrayList<>();
        for (Object o : listKey) {
            SysUser sysUser = JSONObject.parseObject(o.toString(), SysUser.class);
            sysUsers.add(sysUser);
        }
        List<SysUser> sub = CollectionUtil.sub(sysUsers, (pageNo - 1) * pageSize, pageSize);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        List<SysUser> collect =sub;
        if(!StringUtils.isEmpty(search)){
            collect = sub.stream().filter(s -> s.getEmail().contains(search) || s.getNickName().contains(search)).collect(Collectors.toList());

        }
         stringObjectHashMap.put("list",collect);
        stringObjectHashMap.put("total",sysUsers.size());
        return AjaxResult.success(stringObjectHashMap);
    }
    @PostMapping("/delUser")
    public AjaxResult delUser( @RequestBody SignUpVO user){
        Object signUpUserEmail = redisUtil.getCacheObject("signUpUserEmail:" + user.getToken());
        redisUtil.deleteObject("signUpUserEmail:"+user.getToken());
        redisUtil.deleteObject("signUpUserToken:"+signUpUserEmail.toString());
        return AjaxResult.success();
    }


    @PostMapping("/saveUser")
    public AjaxResult saveUser( @RequestBody SignUpVO user)
    {
        String from = DataLoaderConfig.getGlobalData().get("spt.auth.code.email") ; // 发件人邮箱（你的Gmail）
        String host = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.host") ; // SMTP服务器地址
        String port =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.post"); // Gmail SMTP端口
        String username =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.username");
        String password = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.pass");
        SysUser sysUser=null;
        Object signUpUserEmail = redisUtil.getCacheObject("signUpUserEmail:" + user.getToken());
        Object cacheObject = redisUtil.getCacheObject("signUpUserToken:"+signUpUserEmail);
        sysUser = JSONObject.parseObject(cacheObject.toString(), SysUser.class);
        if (sysUser != null) {

            String Account = sysUser.getUserName();

//
//            redisUtil.deleteObject("signUpUserEmail:"+sysUser.getUserName());
//            redisUtil.deleteObject("signUpUserToken:"+signUpUserEmail);
            String to=sysUser.getUserName();
            if(sysUser.getStatus().equals("0")){
                if(user.getIsApprove()){
                    sysUser.setMenuIds(sysUser.getMenuIds());
                    sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
                    baseCommonService.addLog("添加用户，username： " +sysUser.getUserName() , CommonConstant.LOG_TYPE_2, 2);
                    int i = userService.insertUser(sysUser);
                    sysUser.setStatus("1");
                    String jsonString = JSONObject.toJSONString(sysUser);
                    redisUtil.setCacheObject("signUpUserToken:"+signUpUserEmail,jsonString);
                    if(i>0){
                        cachedThreadPool.submit(new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String verificationCode="Registration is successful";
                                if(!user.getIsApprove()){
                                    verificationCode="The request has been denied";
                                }
                                GmailSendVerificationCode.sendEmailWithVerificationCode(to,Account,"Result",verificationCode, from, host, port, username, password);
                            }
                        }));


                        return toAjax(i);
                    }else {

                        return toAjax(true);
                    }

                }else {
                    sysUser.setStatus("2");
                    String    jsonString = JSONObject.toJSONString(sysUser);
                    redisUtil.setCacheObject("signUpUserToken:"+signUpUserEmail,jsonString);
                }
            }
        }
        return AjaxResult.error("Broken links");

    }


}
